package com.freak.kotlinfitnessserver.activity.fragment

import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.lifecycleScope
import com.freak.kotlinfitnessserver.activity.fragment.viewmodel.SupportRangeViewModel
import com.freak.kotlinfitnessserver.app.App
import com.freak.kotlinfitnessserver.constant.DeviceConstant
import com.freak.kotlinfitnessserver.data.FitnessConfigData
import com.freak.kotlinfitnessserver.databinding.FragmentSupportedRangeBinding
import com.freak.kotlinfitnessserver.room.SupportRangeData
import com.freak.kotlinfitnessserver.util.ToastUtil
import kotlinx.coroutines.launch

class SupportedRangeFragment : Fragment() {
    private lateinit var binding: FragmentSupportedRangeBinding

    private lateinit var deviceType: String


    private val supportRangeViewModel: SupportRangeViewModel by activityViewModels {
        SupportRangeViewModel.SupportRangeViewModelFactory((activity?.application as App).fitnessDeviceDatabase.supportRangeDataDao())
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = FragmentSupportedRangeBinding.inflate(inflater, container, false)
        initClickListener()
        initData()
        return binding.root
    }

    private fun initData() {
        arguments ?: let {
            return
        }
        lifecycleScope.launch {
            deviceType = requireArguments().getString(DeviceConstant.deviceType, "")
            binding.linearLayoutSupportedInclinationRange.visibility =
                if (deviceType == DeviceConstant.treadmill) View.VISIBLE else View.GONE
            binding.linearLayoutSupportedSpeedRange.visibility =
                if (deviceType == DeviceConstant.treadmill || deviceType == DeviceConstant.indoorBike) View.VISIBLE else View.GONE
            binding.linearLayoutSupportedHeartRateRange.visibility =
                if (deviceType == DeviceConstant.treadmill
                    || deviceType == DeviceConstant.indoorBike
                    || deviceType == DeviceConstant.crossTrainer
                ) View.VISIBLE else View.GONE
            val supportRangeDataList = supportRangeViewModel.getSupportRangeList(deviceType)
            if (supportRangeDataList.isEmpty()) {
                return@launch
            }
            var supportInclinationRange: SupportRangeData? = null
            var supportSpeedRange: SupportRangeData? = null
            var supportHeartRateRange: SupportRangeData? = null
            var supportPowerRange: SupportRangeData? = null
            var supportResistanceLevelLevelRange: SupportRangeData? = null
            for (supportRangeData in supportRangeDataList) {
                when (supportRangeData.supportRangeType) {
                    FitnessConfigData.SUPPORT_INCLINATION -> {
                        supportInclinationRange = supportRangeData
                    }

                    FitnessConfigData.SUPPORT_SPEED -> {
                        supportSpeedRange = supportRangeData
                    }

                    FitnessConfigData.SUPPORT_POWER -> {
                        supportPowerRange = supportRangeData
                    }

                    FitnessConfigData.SUPPORT_HEART_RATE -> {
                        supportHeartRateRange = supportRangeData
                    }

                    FitnessConfigData.SUPPORT_RESISTANCE_LEVEL -> {
                        supportResistanceLevelLevelRange = supportRangeData
                    }
                }
            }
            if (deviceType == DeviceConstant.treadmill) {
                supportInclinationRange ?: let {
                    return@launch
                }
                binding.editTextMinInclination.setText(supportInclinationRange.minValue.toString())
                binding.editTextMaxInclination.setText(supportInclinationRange.maxValue.toString())
                binding.editTextMinInclinationIncrement.setText(supportInclinationRange.minIncrement.toString())
            }
            if (deviceType == DeviceConstant.treadmill || deviceType == DeviceConstant.indoorBike) {
                supportSpeedRange ?: let {
                    return@launch
                }
                binding.editTextMinSpeed.setText(supportSpeedRange.minValue.toString())
                binding.editTextMaxSpeed.setText(supportSpeedRange.maxValue.toString())
                binding.editTextMinSpeedIncrement.setText(supportSpeedRange.minIncrement.toString())
            }
            if (deviceType == DeviceConstant.treadmill
                || deviceType == DeviceConstant.indoorBike
                || deviceType == DeviceConstant.crossTrainer
            ) {
                supportHeartRateRange ?: let {
                    return@launch
                }
                binding.editTextMinHeartRate.setText(supportHeartRateRange.minValue.toString())
                binding.editTextMaxHeartRate.setText(supportHeartRateRange.maxValue.toString())
                binding.editTextMinHeartRateIncrement.setText(supportHeartRateRange.minIncrement.toString())
            }
            supportPowerRange ?: let {
                return@launch
            }
            binding.editTextMinPower.setText(supportPowerRange.minValue.toString())
            binding.editTextMaxPower.setText(supportPowerRange.maxValue.toString())
            binding.editTextMinPowerIncrement.setText(supportPowerRange.minIncrement.toString())
            supportResistanceLevelLevelRange ?: let {
                return@launch
            }
            binding.editTextMinResistanceLevel.setText(supportResistanceLevelLevelRange.minValue.toString())
            binding.editTextMaxResistanceLevel.setText(supportResistanceLevelLevelRange.maxValue.toString())
            binding.editTextMinResistanceLevelIncrement.setText(supportResistanceLevelLevelRange.minIncrement.toString())
        }
    }

    private fun initClickListener() {
        binding.buttonSaveSupportRange.setOnClickListener {
            if (TextUtils.isEmpty(getMinPower())) {
                ToastUtil.toastShort("请输入Min Power")
                return@setOnClickListener
            }
            if (TextUtils.isEmpty(getMaxPower())) {
                ToastUtil.toastShort("请输入Max Power")
                return@setOnClickListener
            }
            if (TextUtils.isEmpty(getMinPowerIncrement())) {
                ToastUtil.toastShort("请输入Min Power Increment")
                return@setOnClickListener
            }
            if (TextUtils.isEmpty(getMinResistanceLevel())) {
                ToastUtil.toastShort("请输入Min Resistance Level")
                return@setOnClickListener
            }
            if (TextUtils.isEmpty(getMaxResistanceLevel())) {
                ToastUtil.toastShort("请输入Max ResistanceLevel Level")
                return@setOnClickListener
            }
            if (TextUtils.isEmpty(getMinResistanceLevelIncrement())) {
                ToastUtil.toastShort("请输入Min ResistanceLevel Level Increment")
                return@setOnClickListener
            }
            if (deviceType == DeviceConstant.treadmill) {
                if (TextUtils.isEmpty(getMinInclination())) {
                    ToastUtil.toastShort("请输入Min Inclination")
                    return@setOnClickListener
                }
                if (TextUtils.isEmpty(getMaxInclination())) {
                    ToastUtil.toastShort("请输入Max Inclination")
                    return@setOnClickListener
                }
                if (TextUtils.isEmpty(getMinInclinationIncrement())) {
                    ToastUtil.toastShort("请输入Min Inclination Increment")
                    return@setOnClickListener
                }
            }
            if (deviceType == DeviceConstant.treadmill || deviceType == DeviceConstant.indoorBike) {
                if (TextUtils.isEmpty(getMinSpeed())) {
                    ToastUtil.toastShort("请输入Min Speed")
                    return@setOnClickListener
                }
                if (TextUtils.isEmpty(getMaxSpeed())) {
                    ToastUtil.toastShort("请输入Max Speed")
                    return@setOnClickListener
                }
                if (TextUtils.isEmpty(getMinSpeedIncrement())) {
                    ToastUtil.toastShort("请输入Min Speed Increment")
                    return@setOnClickListener
                }
            }
            if (deviceType == DeviceConstant.treadmill
                || deviceType == DeviceConstant.indoorBike
                || deviceType == DeviceConstant.crossTrainer
            ) {
                if (TextUtils.isEmpty(getMinHeartRate())) {
                    ToastUtil.toastShort("请输入Min Heart Rate")
                    return@setOnClickListener
                }
                if (TextUtils.isEmpty(getMaxHeartRate())) {
                    ToastUtil.toastShort("请输入Max Heart Rate")
                    return@setOnClickListener
                }
                if (TextUtils.isEmpty(getMinHeartRateIncrement())) {
                    ToastUtil.toastShort("请输入Min Heart Rate Increment")
                    return@setOnClickListener
                }
            }
            lifecycleScope.launch {
                // 保存到数据库
                val supportRangeDataList = supportRangeViewModel.getSupportRangeList(deviceType)
                if (supportRangeDataList.isEmpty()) {
                    // 插入数据
                    if (deviceType == DeviceConstant.treadmill) {
                        val supportInclinationRange = SupportRangeData(
                            deviceType = deviceType,
                            supportRangeType = FitnessConfigData.SUPPORT_INCLINATION,
                            minValue = getMinInclination().toInt(),
                            maxValue = getMaxInclination().toInt(),
                            minIncrement = getMinInclinationIncrement().toInt()
                        )
                        supportRangeViewModel.insertSupportRangeData(supportInclinationRange)
                    }
                    if (deviceType == DeviceConstant.treadmill || deviceType == DeviceConstant.indoorBike) {
                        val supportSpeedRange = SupportRangeData(
                            deviceType = deviceType,
                            supportRangeType = FitnessConfigData.SUPPORT_SPEED,
                            minValue = getMinSpeed().toInt(),
                            maxValue = getMaxSpeed().toInt(),
                            minIncrement = getMinSpeedIncrement().toInt()
                        )
                        supportRangeViewModel.insertSupportRangeData(supportSpeedRange)
                    }
                    if (deviceType == DeviceConstant.treadmill
                        || deviceType == DeviceConstant.indoorBike
                        || deviceType == DeviceConstant.crossTrainer
                    ) {
                        val supportHeartRateRange = SupportRangeData(
                            deviceType = deviceType,
                            supportRangeType = FitnessConfigData.SUPPORT_HEART_RATE,
                            minValue = getMinHeartRate().toInt(),
                            maxValue = getMaxHeartRate().toInt(),
                            minIncrement = getMinHeartRateIncrement().toInt()
                        )
                        supportRangeViewModel.insertSupportRangeData(supportHeartRateRange)
                    }
                    val supportPowerRange = SupportRangeData(
                        deviceType = deviceType,
                        supportRangeType = FitnessConfigData.SUPPORT_POWER,
                        minValue = getMinPower().toInt(),
                        maxValue = getMaxPower().toInt(),
                        minIncrement = getMinPowerIncrement().toInt()
                    )
                    supportRangeViewModel.insertSupportRangeData(supportPowerRange)
                    val supportResistanceLevelLevelRange = SupportRangeData(
                        deviceType = deviceType,
                        supportRangeType = FitnessConfigData.SUPPORT_RESISTANCE_LEVEL,
                        minValue = getMinResistanceLevel().toInt(),
                        maxValue = getMaxResistanceLevel().toInt(),
                        minIncrement = getMinResistanceLevelIncrement().toInt()
                    )
                    supportRangeViewModel.insertSupportRangeData(supportResistanceLevelLevelRange)
                    return@launch
                }
                // 更新数据
                var updateSupportInclinationRange: SupportRangeData? = null
                var updateSupportSpeedRange: SupportRangeData? = null
                var updateSupportHeartRateRange: SupportRangeData? = null
                var updateSupportPowerRange: SupportRangeData? = null
                var updateSupportResistanceLevelLevelRange: SupportRangeData? = null
                for (supportRangeData in supportRangeDataList) {
                    when (supportRangeData.supportRangeType) {
                        FitnessConfigData.SUPPORT_INCLINATION -> {
                            updateSupportInclinationRange = supportRangeData
                        }

                        FitnessConfigData.SUPPORT_SPEED -> {
                            updateSupportSpeedRange = supportRangeData
                        }

                        FitnessConfigData.SUPPORT_POWER -> {
                            updateSupportPowerRange = supportRangeData
                        }

                        FitnessConfigData.SUPPORT_HEART_RATE -> {
                            updateSupportHeartRateRange = supportRangeData
                        }

                        FitnessConfigData.SUPPORT_RESISTANCE_LEVEL -> {
                            updateSupportResistanceLevelLevelRange = supportRangeData
                        }
                    }
                }
                if (deviceType == DeviceConstant.treadmill) {
                    updateSupportInclinationRange ?: let {
                        return@launch
                    }
                    val supportInclinationRange = SupportRangeData(
                        id = updateSupportInclinationRange.id,
                        deviceType = updateSupportInclinationRange.deviceType,
                        supportRangeType = updateSupportInclinationRange.supportRangeType,
                        minValue = getMinInclination().toInt(),
                        maxValue = getMaxInclination().toInt(),
                        minIncrement = getMinInclinationIncrement().toInt()
                    )
                    supportRangeViewModel.updateSupportRangeData(supportInclinationRange)
                }
                if (deviceType == DeviceConstant.treadmill || deviceType == DeviceConstant.indoorBike) {
                    updateSupportSpeedRange ?: let {
                        return@launch
                    }
                    val supportSpeedRange = SupportRangeData(
                        id = updateSupportSpeedRange.id,
                        deviceType = updateSupportSpeedRange.deviceType,
                        supportRangeType = updateSupportSpeedRange.supportRangeType,
                        minValue = getMinSpeed().toInt(),
                        maxValue = getMaxSpeed().toInt(),
                        minIncrement = getMinSpeedIncrement().toInt()
                    )
                    supportRangeViewModel.updateSupportRangeData(supportSpeedRange)
                }
                if (deviceType == DeviceConstant.treadmill
                    || deviceType == DeviceConstant.indoorBike
                    || deviceType == DeviceConstant.crossTrainer
                ) {
                    updateSupportHeartRateRange ?: let {
                        return@launch
                    }
                    val supportHeartRateRange = SupportRangeData(
                        id = updateSupportHeartRateRange.id,
                        deviceType = updateSupportHeartRateRange.deviceType,
                        supportRangeType = updateSupportHeartRateRange.supportRangeType,
                        minValue = getMinHeartRate().toInt(),
                        maxValue = getMaxHeartRate().toInt(),
                        minIncrement = getMinHeartRateIncrement().toInt()
                    )
                    supportRangeViewModel.updateSupportRangeData(supportHeartRateRange)
                }
                updateSupportPowerRange ?: let {
                    return@launch
                }
                val supportPowerRange = SupportRangeData(
                    id = updateSupportPowerRange.id,
                    deviceType = updateSupportPowerRange.deviceType,
                    supportRangeType = updateSupportPowerRange.supportRangeType,
                    minValue = getMinPower().toInt(),
                    maxValue = getMaxPower().toInt(),
                    minIncrement = getMinPowerIncrement().toInt()
                )
                supportRangeViewModel.updateSupportRangeData(supportPowerRange)
                updateSupportResistanceLevelLevelRange ?: let {
                    return@launch
                }
                val supportResistanceLevelLevelRange = SupportRangeData(
                    id = updateSupportResistanceLevelLevelRange.id,
                    deviceType = updateSupportResistanceLevelLevelRange.deviceType,
                    supportRangeType = updateSupportResistanceLevelLevelRange.supportRangeType,
                    minValue = getMinResistanceLevel().toInt(),
                    maxValue = getMaxResistanceLevel().toInt(),
                    minIncrement = getMinResistanceLevelIncrement().toInt()
                )
                supportRangeViewModel.updateSupportRangeData(supportResistanceLevelLevelRange)
            }
        }
    }

    private fun getMinSpeed(): String {
        return binding.editTextMinSpeed.text.trim().toString()
    }

    private fun getMaxSpeed(): String {
        return binding.editTextMaxSpeed.text.trim().toString()
    }

    private fun getMinSpeedIncrement(): String {
        return binding.editTextMinSpeedIncrement.text.trim().toString()
    }

    private fun getMinInclination(): String {
        return binding.editTextMinInclination.text.trim().toString()
    }

    private fun getMaxInclination(): String {
        return binding.editTextMaxInclination.text.trim().toString()
    }

    private fun getMinInclinationIncrement(): String {
        return binding.editTextMinInclinationIncrement.text.trim().toString()
    }

    private fun getMinHeartRate(): String {
        return binding.editTextMinHeartRate.text.trim().toString()
    }

    private fun getMaxHeartRate(): String {
        return binding.editTextMaxHeartRate.text.trim().toString()
    }

    private fun getMinHeartRateIncrement(): String {
        return binding.editTextMinHeartRateIncrement.text.trim().toString()
    }

    private fun getMinPower(): String {
        return binding.editTextMinPower.text.trim().toString()
    }

    private fun getMaxPower(): String {
        return binding.editTextMaxPower.text.trim().toString()
    }

    private fun getMinPowerIncrement(): String {
        return binding.editTextMinPowerIncrement.text.trim().toString()
    }

    private fun getMinResistanceLevel(): String {
        return binding.editTextMinResistanceLevel.text.trim().toString()
    }

    private fun getMaxResistanceLevel(): String {
        return binding.editTextMaxResistanceLevel.text.trim().toString()
    }

    private fun getMinResistanceLevelIncrement(): String {
        return binding.editTextMinResistanceLevelIncrement.text.trim().toString()
    }

    companion object {
        @JvmStatic
        fun newInstance(deviceType: String) = SupportedRangeFragment().apply {
            arguments = Bundle().apply {
                putString(DeviceConstant.deviceType, deviceType)
            }
        }
    }
}